import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as fse from 'fs-extra'
import * as vscode from 'vscode';
import localize from './localize';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
import { resolveLicensePack } from './extension';

/**
 * 存储共用的函数
 */

 const debPath = "/usr/bin/dpkg";
 const rpmPath = "/usr/bin/rpmbuild";
 const rpmType = "RpmPackage";
 const debType = "DebPackage";

// 判断系统包管理类型
export async function getPackageType(viewPanel: any) {
    
    var type = isFileExist(debPath) ? debType : rpmType;

    // rpm 和 deb 命令都查询不到
    if(!isFileExist(debPath) && !isFileExist(rpmPath)) {
        showInfo(localize("language.isRpmDebCommandExist"));
    }

    // 发送消息
	viewPanel.webview.postMessage({
	    type: 'JUDGE_PACKAGE_TYPE',
		value: type
	});
}

/**
 * 
 * @param str 检查是否为未定义或空
 * @returns 
 */
export function isEmpty(str: any){
    return str == undefined || str == ""
}
/**
 * 
 * @param str 检查是否不为空和undefined
 * @returns 
 */
export function isNotEmpty(str: any){
    return !isEmpty(str);
}


// 打印获取系统类型
export function getSystemPlatform() {
    const platform = os.platform()
    switch (platform) {
        case 'darwin':
            console.log("MacOSX")
            break;
        case 'linux':
            console.log('Linux')
            break;
        case 'win32':
            console.log('Windows')
            break;
        default:
            console.log("无法确定操作系统!")
    }
    return platform;
   }
   // 判断是否linux
   export function isLinux(){
       return os.platform() === "linux";
   }
// 获取当前年
export function getYear(){
    return (new Date()).getFullYear();
}

export async function isExecutableFilePath(path: string):Promise<boolean> {
    // 路径存在返回 true
    if(fs.existsSync(path)) return true;

    // 假设是可执行文件名的情况，which 查找出路径
    const out = await getCommandPath(path);
    if(!out.length) return false;
    if(!fs.existsSync(out)) return false;
    return true;
}

export async function chooseProjectDirectory(viewPanel: any, type: string) {
    let options = {
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        //defaultUri: vscode.Uri.file("/home/"),	//The folder opened by default
        openLabel: localize("language.chooseProjectDir")
    };
    // 选择框
    vscode.window.showOpenDialog(options).then(result => {
        if (result != undefined) {
            var loadUri = result[0].path.toString();
            viewPanel.webview.postMessage({
                type: 'CHOOSE_DIR',
                value: loadUri
            });
        }
    });
}

//生成perf data
export async function getperfdata(projectPath: string){  
    var output = execSync(`perf record -g -e cpu-clock ${projectPath}`);
    var output = execSync(`perf report -i /home/kylin/.kylin-ide/extensions/create-project-template/perf.data > perf.txt`);
    //console.log(projectPath);
    //var output = execSync(`echo "${projectPath}"`);
}

//打开txt文件
export async function opentxtfile(filePath: string){  
    const path = '/home/kylin/.kylin-ide/extensions/create-project-template/perf.txt';
    vscode.window.showTextDocument(vscode.Uri.file(path));
}

export async function chooseBinaryfileDirectory(viewPanel: any, type: string) {
    let options = {
        canSelectFiles: true,
        canSelectFolders: false,
        canSelectMany: false,
        //defaultUri: vscode.Uri.file("/home/"),	//The folder opened by default
        openLabel: localize("language.chooseBinaryfile")
    };
    // 选择框
    vscode.window.showOpenDialog(options).then(result => {
        if (result != undefined) {
            var loadUri = result[0].path.toString();
            viewPanel.webview.postMessage({
                type: 'CHOOSE_FILE',
                value: loadUri
            });
        }
    });
}

/**
 * @description: 读取用户路径，启用了默认路径逻辑
 *      这里采用了数据存储（Data Storage）：
 *      有4种数据存储的方式（注：extension context在入口文件的activate函数中可用，是该函数的第一个参数）
 *          ExtensionContext.workspaceState：工作空间（workspace）域，
 *              以键值对方式存储，由VS Code负责管理。当工作空间再次被打开时，存储的数据会被恢复。
 *          ExtensionContext.globalState：全局域，
 *              以键值对方式存储，由VS Code负责管理。当任何一个插件被激活时，，存储的数据会被恢复。插件可以同步的读取到键值对数据并且通过setKeysForSync方法异步的赋值
 *          ExtensionContext.storagePath：工作空间（workspace）域，
 *              可以为一个工作空间指定一个存储路径（一个本地的目录），当我们需要给一个工作空间存储较大的数据时（例如文件），该功能非常有用
 *          ExtensionContext.globalStoragePath：全局域，
 *              可以为全局空间指定一个存储路径（一个本地的目录），当我们需要在不同的插件之间共用大的数据时（例如文件），该功能非常有用
 * @param {vscode} conext
 * @param {vscode} viewPanel
 * @return {*}
 * @author: kylinos.cn
 */
 export function onGetHomePath(conext: vscode.ExtensionContext, viewPanel: vscode.WebviewPanel) {

    const homedir = os.homedir();
    // 读取判断标志
    // 为真时，默认路径有效
    let isSaveDir = conext.globalState.get("IS_SAVE_DIR");
    // 判断标志 转boolean
    isSaveDir = isSaveDir == undefined || isSaveDir == "false" ? false : true;
    // 读取已保存路径
    const mydir = conext.globalState.get("MY_DIR");
    //   console.log("get IS_SAVE_DIR : " + isSaveDir );
    //   console.log("get MY_DIR : " + mydir );
    // 发送消息
    viewPanel.webview.postMessage({
        // 消息类型: 用户路径
        type: "GET_HOME_DIR",
        isSaveDir: isSaveDir,
        // 根据判断标志，返回保存路径或home路径
        value: isSaveDir ? mydir : homedir
    });
    return true;
}
/**
 * 根据 projectType 返回homePath或者缓存path，以及更多其他path数据
 * @param conext 
 * @param viewPanel 
 * @param projetType 
 * @returns 
 */
export function onGetPaths(conext: vscode.ExtensionContext, viewPanel: vscode.WebviewPanel, projectType?: string) {

   const homedir = os.homedir();
   // 读取判断标志
   // 为真时，默认路径有效
   let isSaveDir = conext.globalState.get("IS_SAVE_DIR");
   // 判断标志 转boolean
   isSaveDir = isSaveDir == undefined || isSaveDir == "false" ? false : true;
   // 读取已保存路径
   const mydir = conext.globalState.get("MY_DIR");
   //   console.log("get IS_SAVE_DIR : " + isSaveDir );
   //   console.log("get MY_DIR : " + mydir );
   let obj = {
        projectPath: (isSaveDir ? mydir : homedir) as string,
        jdkPath: '',
    };
   if(projectType === "java"){
       // 额外返回jdk路径
       let configJavaHome = getJdtlsConfigJavaHome();
       let javaHome = getJavaHome();
        obj.jdkPath = configJavaHome != undefined ? configJavaHome : javaHome as string;
   }
   // 发送消息
   viewPanel.webview.postMessage({
       // 消息类型: 用户路径
       type: "GET_HOME_DIR",
       isSaveDir: isSaveDir,
        value: isSaveDir ? mydir : homedir,
       object: obj
    });
    return true;
}

// 您必须使用java.jdt.ls.java.home 而不是java.home，因为它已被弃用，此设置可能会在更高版本的 VS Code 中被删除
// export function getConfigJavaHome(): string | null {
//     return vscode.workspace.getConfiguration("java").get<string | null>("home", null);
// }

export function getJdtlsConfigJavaHome(): string | null {
    return vscode.workspace.getConfiguration("java").get<string | null>("jdt.ls.java.home", null);
}

// 您必须使用java.jdt.ls.java.home 而不是java.home，因为它已被弃用，此设置可能会在更高版本的 VS Code 中被删除
// export function setConfigJavaHome(home: string) {
//     return vscode.workspace.getConfiguration("java").update("home", home, false);
// }

export function setJdtlsConfigJavaHome(home: string) {
    vscode.workspace.getConfiguration("java").update('jdt.ls.java.home', home, false);
}

export function getJavaHome(): string | undefined {
    return process.env.JAVA_HOME;
}

/**
 * @description: 保存默认路径相关，采用全局域存储
 *      这里采用了数据存储（Data Storage）：
 *      有4种数据存储的方式（注：extension context在入口文件的activate函数中可用，是该函数的第一个参数）
 *          ExtensionContext.workspaceState：工作空间（workspace）域，
 *              以键值对方式存储，由VS Code负责管理。当工作空间再次被打开时，存储的数据会被恢复。
 *          ExtensionContext.globalState：全局域，
 *              以键值对方式存储，由VS Code负责管理。当任何一个插件被激活时，，存储的数据会被恢复。插件可以同步的读取到键值对数据并且通过setKeysForSync方法异步的赋值
 *          ExtensionContext.storagePath：工作空间（workspace）域，
 *              可以为一个工作空间指定一个存储路径（一个本地的目录），当我们需要给一个工作空间存储较大的数据时（例如文件），该功能非常有用
 *          ExtensionContext.globalStoragePath：全局域，
 *              可以为全局空间指定一个存储路径（一个本地的目录），当我们需要在不同的插件之间共用大的数据时（例如文件），该功能非常有用
 * @param {vscode} conext
 * @param {Boolean} isSaveDir
 * @param {String} path
 * @return {*}
 * @author: kylinos.cn
 */
export function onSetDir(conext: vscode.ExtensionContext, isSaveDir: Boolean, path: String) {
    // 保存判断标志
    conext.globalState.update("IS_SAVE_DIR", isSaveDir + "");
    // 保存路径
    conext.globalState.update("MY_DIR", path);
}
// sync
export function onChoosePrjDir(conext: vscode.ExtensionContext, viewPanel: any, model?: any) {
    let options = {
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        openLabel: localize("language.chooseProjectDir")
    };
    vscode.window.showOpenDialog(options).then(result => {
        if (result === undefined) {
            vscode.window.showInformationMessage("language.OperationCancelled");
        }
        else {
            // 获取选中的路径
            var loadUri = result[0].path.toString();
            // var loadDir = loadUri.substr(0,  loadUri.length);
            // 检查是否需要保存路径
            let isSaveDir = conext.globalState.get("IS_SAVE_DIR");
            isSaveDir = isSaveDir == undefined || isSaveDir == "false" ? false : true;
            console.log("get IS_SAVE_DIR : " + isSaveDir);
            if (isSaveDir) {
                // 存储选择的路径
                conext.globalState.update("MY_DIR", loadUri);
                console.log("update MY_DIR : " + loadUri);
            }
            viewPanel.webview.postMessage({
                type: 'CHOOSE_DIR',
                value: loadUri,
                model: model
            });
        }
    })
}

export async function getCommandOutput(cmd: string): Promise<string> {
    var output = execSync(cmd);
    var str = output.toString();
    if (str[str.length - 1] == '\n') {
        str = str.substring(0, str.length - 1);
    }
    return str;
}

export function getCommandOutputSync(cmd: string): string {
    var output = execSync(cmd);
    var str = output.toString();
    if (str[str.length - 1] == '\n') {
        str = str.substring(0, str.length - 1);
    }
    return str;
}


/**
 * 弹出提示信息
 * @param info 提示信息
 */
export function showInfo(info: any) {
    vscode.window.showInformationMessage(info);
}

/**
 * 弹出错误信息
 * @param info 错误信息
 */
export function showError(info: any) {
    vscode.window.showErrorMessage(info);
}

/**
 * 创建目录
 * @param dir 路径 
 * @param options 参数
 */
export async function createDir(dir: string, options?: any) {
    try {
        fse.ensureDirSync(dir, options);
    } catch (err) {
        console.error(err);
    }
}

/**
 * 判断 Java Maven groupId 是否合法
 * @param groupId 
 * @returns 
 */
export async function isProjectGroupId(groupId: string) {
    var reg = RegExp("[^0-9a-zA-Z.]");
    if (groupId.match(reg)) {
        return false;
    }
    return true;
}

/**
 * 判断项目名称是否合法
 * @param name 项目名称
 * @returns 
 */
export async function isProjectNameLegal(projectName: string): Promise<boolean> {
    var reg = RegExp("[^0-9a-zA-Z_-]");
    if ( projectName.match(reg)) {
        return false;
    }
    return true;
}

/**
 * 判断项目路径是否合法以及项目名称在路径下是否已经存在
 * @param projectPath 项目路径
 * @param projectName 项目名称
 * @returns 
 */
export async function isProjectPathLegal(projectPath: string, projectName: string): Promise<string> {
    //判断项目目录是否存在
    if (!fs.existsSync(projectPath)) {
        return localize("language.errorProjectPath");
    }
    //判断 projectPath/projectName 是否存在
    if (fs.existsSync(path.join(projectPath, projectName))) {
        return localize("language.errorProjectNameExist");
    }
    return '';
}

export function isProjectPathLegalSync(projectPath: string, projectName: string) {
    //判断项目目录是否存在
    if (!fs.existsSync(projectPath)) {
        return false;
    }
    //判断 projectPath/projectName 是否存在
    if (!fs.existsSync(path.join(projectPath, projectName))) {
        return false;
    }
    return true;
}

/**
 * 判断路径是否合法
 * @param path 路径
 * @returns 
 */
export function isPathLegalSync(path: string) {
    if (!fs.existsSync(path)) {
        return false;
    }
    return true;
}

/**
 * 判断项目文件命名是否合法
 * @param projectFile 项目文件名
 * @returns 
 */
export function isFileNameLegalSync(file: string) {
    var reg = RegExp("[^0-9a-zA-Z_]");
    if (file.match(reg)) {
        return false
    }
    return true;
}

/**
 * 判断项目文件命名是否合法
 * @param projectFile 项目文件名
 * @returns 
 */
export async function isProjectFileLegal(projectFile: string): Promise<boolean> {
    var reg = RegExp("[^0-9a-zA-Z_]");
    if (projectFile.match(reg)) {
        return false;
    }
    return true;
}

/**
 * 判断项目文件命名是否合法
 * @param projectFile 项目文件名
 * @returns 
 */
export function isProjectFileLegalSync(projectFile: string) {
    var reg = RegExp("[^0-9a-zA-Z_]");
    if (projectFile.match(reg)) {
        return false;
    }
    return true;
}

/**
 * 获取系统命令路径
 * @param cmd 命令名称
 * @returns 
 */
export async function getCommandPath(cmd: string): Promise<string> {
    var path = '';
    try {
        var output = execSync(`which ${cmd}`);
        path = output.toString();
    } catch (error) {
        console.log('Error: ' + error);
        return '';
    }
    if(!path.length) return '';
    if (path[path.length - 1] == '\n') {
        path = path.substring(0, path.length - 1);
    }
    return path;
}

/**
 * 检查是否存在该目录
 * @param dirPath 目录
 * @returns 
 */
export function isDirExist(dirPath: string): boolean {
    return fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory();
}
/**
* 检查是否存在该文件
* @param filePath 文件路径
* @returns 
*/
export function isFileExist(filePath: string): boolean {
    return fs.existsSync(filePath) && fs.statSync(filePath).isFile();
}

/**
* 检查字符串str是否以startstr开始
* @param str 字符串
*  @param startstr 子字符串
* @returns 
*/
export function isStartWith(str: string, startstr: string): boolean {
    var d = str.length;
    return (d > 0 && str.indexOf(startstr) == 0);

}

/**
*  检查字符串str是否以endstr结尾
* @param str 字符串
*  @param endstr 子字符串
* @returns 
*/
export function isEndWith(str: string, endstr: string): boolean {
    var d = str.length - endstr.length;
    return (d >= 0 && str.indexOf(endstr) == d)
}


/**
*  检查deb包是否安装
* @param debName 包名
* @returns 
*/
export function debIsInstalled(debName: string): boolean {
    var res = false;
    try {
        var output = execSync(`dpkg -s ${debName}`);
        var Info = output.toString();
        var tmp = Info.split("\n");
        for (let str of tmp) {
            if (isStartWith(str, "Status:") && isEndWith(str, "install ok installed")) {
                res = true;
                break;
            }

        }
    }
    catch (error) { };
    return res;
}

/**
*  检查rpm包是否安装
* @param rpmName 包名
* @returns 
*/
export function rpmIsInstalled(rpmName: string): boolean {
    var res = false;
    try {
        execSync(`rpm -q ${rpmName}`);
        res = true;
    }
    catch (error) { };
    return res;
}


export function isInstalledopenssllib(): boolean {
    if (isDirExist("/etc/apt")) {
        return debIsInstalled("libssl-dev");
    } else {
        return rpmIsInstalled("openssl-devel");
    }
}


export function isInstalledopenmpilib(): boolean {
    if (isDirExist("/etc/apt")) {
        return debIsInstalled("libopenmpi-dev");
    } else {
        return rpmIsInstalled("openmpi-devel");
    }
}


export function isInstalledopencvlib(): boolean {
    if (isDirExist("/etc/apt")) {
        return debIsInstalled("libopencv-dev");
    } else {
        return rpmIsInstalled("opencv-devel");
    }
}

export function isInstalledopencllib() {
    if (isDirExist("/etc/apt")) {
        return debIsInstalled("libclc-dev");
    } else {
        return rpmIsInstalled("opencl-devel");
    }
}

export function isDebOS():boolean{
    var res=false;
    if(isDirExist("/etc/apt"))
        res=true;
    return res;
}

//x86_64
//mips64
//sw_64
//aarch64
export function cmdArch():string{
    var res="";
    try {
        var output=execSync(`arch`);
        var Info = output.toString();
        res=Info;
    }
      catch(error){};
    return res;
}

export function getArchStr():string{
    var str="";
    if(cmdArch()==="x86_64"|| isDirExist("/usr/include/x86_64-linux-gnu"))
        str = "x86_64-linux-gnu";
    else if(cmdArch()==="aarch64"||isDirExist("/usr/include/aarch64-linux-gnu")){
        str = "aarch64-linux-gnu"
    }else if(cmdArch()==="mips64" || isDirExist("/usr/include/mips64el-linux-gnuabi64")){
        str = "mips64el-linux-gnuabi64"
    }else if(cmdArch()==="sw_64"){
        str = "sw_64-linux-gnuabi64"
    }
    return str;
}

export function getOpenclInclude():string[]{
    var openclpath:string [] = new Array();
    if(isDebOS()){
        openclpath.push("-I/usr/include/CL");
    }

    return openclpath;
}

export function getOpenmpiIncludepkg(lang?:string):string[]{
    var openmpiIncludePath:string[] = new Array();
    var openmpiIncludeStr:string;
    if(lang!=undefined){
        openmpiIncludeStr = getCommandOutputSync("pkg-config --cflags-only-I ompi-cxx");
    }else{
        openmpiIncludeStr = getCommandOutputSync("pkg-config --cflags-only-I ompi-c");
    }
    openmpiIncludePath=openmpiIncludeStr.split(" ");
    //string convert to string[]
    console.log(openmpiIncludePath);
    return openmpiIncludePath;

}
export function getOpenmpiLibDirpkg(lang?:string):string[]{
    var openmpiLibDir:string[] = new Array();
    var openmpiLibStr:string;
    if(lang!=undefined){
        openmpiLibStr = getCommandOutputSync("pkg-config --libs-only-L ompi-cxx");
    }else{
        openmpiLibStr = getCommandOutputSync("pkg-config --libs-only-L ompi-c");
    }
    openmpiLibDir=openmpiLibStr.split(" ");
    //string convert to string[]
    console.log(openmpiLibDir);
    return openmpiLibDir;

}

export function getOpenmpiInclude():string[]{
    var openmpipath:string[] = new Array();
    var archStr:string;
    if(isDirExist("/etc/apt")){
        archStr = getArchStr();
        openmpipath.push(`-I/usr/lib/${archStr}/openmpi/include`);
        openmpipath.push(`-I/usr/lib/${archStr}/openmpi/include/openmpi`);
    }

    return openmpipath;
}

export function getOpensslInclude():string[]{
    var opensslpath:string [] = new Array();
        opensslpath.push("-I/usr/include/openssl");
    return opensslpath;
}

export function getOpensslLib():string[]{
    var openssllib:string[]=new Array();
    openssllib.push("-lssl");
    openssllib.push("-lcrypto");
    return openssllib;
}
export function getOpenmpiLib(lang?:string):string[]{
    var openmpilib:string[]=new Array();
    openmpilib.push("-lmpi");
    if(lang!== undefined && lang === "c++"){
        openmpilib.push("-lmpi_cxx");
    }
    return openmpilib;
}
export function getOpenmpiLibDir():string[]{
    var openmpiLibDir:string[] = new Array();
    var archStr:string;
    archStr = getArchStr();
    openmpiLibDir.push(`-L/usr/lib/${archStr}/openmpi/lib`);
    return openmpiLibDir;
}

export function getAllOpenmpiArgs(lang?:string):string[]{
    var openmpiallargs:string[] = new Array();
    openmpiallargs.push("-pthread");
    if(lang != undefined && lang === "c++"){
        openmpiallargs = openmpiallargs.concat(getOpenmpiIncludepkg(lang));
        openmpiallargs = openmpiallargs.concat(getOpenmpiLibDirpkg(lang));
        openmpiallargs = openmpiallargs.concat(getOpenmpiLib(lang));
    } 
    else{
        openmpiallargs = openmpiallargs.concat(getOpenmpiIncludepkg());
        openmpiallargs = openmpiallargs.concat(getOpenmpiLibDirpkg());
        openmpiallargs = openmpiallargs.concat(getOpenmpiLib());
    }
    return openmpiallargs;
}

// substrAry is the sub of strAry
export function isSub(strAry:string[],substrAry:string[]):boolean{
   var substrArylen=substrAry.length;
   var tempArr = substrAry.filter(item=>{
       return strAry.includes(item);})
    if(tempArr.length === substrArylen){
        return  true;
    }else{
        return false;
    }
    return true;
}
//数组去重
export function uniqueArray(arr:string[]) {
    var array:string[]=new Array();
    for(var i = 0; i < arr.length; i++) {
        if( !array.includes( arr[i])) {
            array.push(arr[i]); 
        } 
    }
    return array ;
}
//删除指定的子集
export function removeSub(arr:string[],subarr:string[]):string[]{
    for(var i=0;i<arr.length;i++){
        for(var j=0;j< subarr.length;j++){
            if( arr[i] === subarr[j]){
                arr.splice(i,1);
            }
        }
    }
    return arr;
}

export function getIncludeDir(args:string[]):string[]{
    var IncludeDirArray:string[]=new Array();
    for(var i=0 ; i<args.length ; i++){
        if(isStartWith(args[i],"-I")){
            IncludeDirArray.push(args[i]);
        }
    }
    return IncludeDirArray;
}
export function getLibDir(args:string[]):string[]{
    var LibDirArray:string[]=new Array();
    for(var i=0 ; i<args.length ; i++){
        if(isStartWith(args[i],"-I")){
            LibDirArray.push(args[i]);
        }
    }
    return LibDirArray;
}
export function getLib(args:string[]):string[]{
    var libArray:string[]=new Array();
    for(var i=0 ; i<args.length ; i++){
        if(isStartWith(args[i],"-l")){
            libArray.push(args[i]);
        }
    }
    return libArray;
}
export function getSource(args:string[]):string[]{
    var SourceArray:string[]=new Array();
    for(var i=0 ; i<args.length ; i++){
        if(isEndWith(args[i],".c")){
            SourceArray.push(args[i]);
        }
    }
    return SourceArray;
}

export function isProjectValid(prjPath: string, prjName: string, execFile: string): boolean {
    if (!isFileNameLegalSync(execFile)) {
        let msg = localize("language.errorName");
        showInfo(execFile + " : " + msg);
        return false;
    }

    if (!isFileNameLegalSync(prjName)) {
        let msg = localize("language.errorName");
        showInfo(prjName + " : " + msg);
        return false;
    }

    if (!isPathLegalSync(prjPath)) {
        let msg = localize("language.errorPath");
        showInfo(prjPath + " : " + msg);
        return false;
    }

    let prjFullPath = `${prjPath}/${prjName}`;

    if (isPathLegalSync(prjFullPath)) {
        let msg = localize("language.errorProjectNameExist");
        showInfo(prjFullPath + " : " + msg);
        return false;
    }

    fs.mkdirSync(prjFullPath, { recursive: true });
    return true;
}

export function resetBlank(str: string) {
    let regEx = /\s+/g;
    return str.trim().replace(regEx, ' ');
};

export function getNonce() {
	let text = '';
	const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	for (let i = 0; i < 32; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	}
	return text;
}

export function buildInclude(webviewPath:string, data: string, fileFolderPath: string): string {
    // console.log(data)
    const reg = new RegExp(`<include path="(.+?)" (\\/)?>`, "ig");
    let match = reg.exec(data);
    while (match != null) {
      const includePath = match[1].startsWith("/")
        ? webviewPath + match[1]
        : fileFolderPath + match[1];
      const includeContent = fs.readFileSync(includePath, "utf8");
      if (includeContent) {
        data = data.replace(match[0], includeContent);
      }
      match = reg.exec(data);
    }
    // console.log(data)
    return data;
  }

  export function buildPath(
    data: string,
    webview: vscode.Webview,
    parentPath: string
  ): string {
    return data.replace(
      /("|')\/?(css|js|components)\b/gi,
      "$1" + webview.asWebviewUri(vscode.Uri.file(`${parentPath}/`)) + "/$2"
    );
  }